package com.htt.app.blogradio.view;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.HeaderViewListAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.htt.app.blogradio.BlogRadio;
import com.htt.app.blogradio.R;
import com.htt.app.blogradio.adapter.ListShowAdapter;
import com.htt.app.blogradio.config.Config;
import com.htt.app.blogradio.dialog.MyProgressDialog;
import com.htt.app.blogradio.jsonparsing.JSONParser;
import com.htt.app.blogradio.object.Show;
import com.htt.app.blogradio.server.Server;

public class ShowView implements OnClickListener, OnScrollListener{
	public boolean isCreate = false;
	
	private ListView listView;
	private Activity activity;

	private ImageButton btnRefresh;
	private TextView tvTitle;
	private ImageView btnBack;
	
	private View view;
	
	private View footerView;
	private boolean loading = false;
	private boolean moreRows = true;
	
	private int page = 0;
	
	public View createView(Activity context) {
		// TODO Auto-generated constructor stub
		activity = context;
		view = LayoutInflater.from(context).inflate(R.layout.list, null);
		
		listView = (ListView) view.findViewById(R.id.list);
		btnRefresh = (ImageButton) view.findViewById(R.id.list_header_refresh);
		tvTitle = (TextView) view.findViewById(R.id.list_header_title);
		
		
		if(btnRefresh.getVisibility() == View.GONE) {
			btnRefresh.setVisibility(View.VISIBLE);
		}
		
		btnRefresh.setOnClickListener(this);
		listView.setOnScrollListener(this);

		footerView = ((LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer, null, false);
		
		loadData();
		isCreate = true;
		
		return view;
	}
	public void loadData() {
		page = 0;
		
		new AsyncTask<Void, Void, Void>() {
			
			private MyProgressDialog progress;
			private List<Show> data = new ArrayList<Show>();
			
			protected void onPreExecute() {
				progress = new MyProgressDialog(activity);
				progress.startProgress("", activity.getResources().getString(R.string.loading));
			};
			
			@Override
			protected Void doInBackground(Void... params) {
				// TODO Auto-generated method stub
				Server server = new Server(Config.URL_SHOW(page++));
				JSONParser jsonParser = new JSONParser();
				data = jsonParser.getListShow(server.getJsonArray());
				return null;
			}
			
			protected void onPostExecute(Void result) {
				progress.stopProgress();
				if(data != null && data.size() > 0) {
					setData(data);
				} else
					Toast.makeText(activity, activity.getResources().getString(R.string.loading_error), 
							Toast.LENGTH_LONG).show();
			};
			
		}.execute();
	}
	
	public View getView() {
		return view;
	}
	
	/*
	 *  set data for display
	 */
	
	public void setData(List<Show> data) {
		if(data != null && data.size() > 0) {
			
			ListShowAdapter adapter = new ListShowAdapter(activity, R.layout.list_show_item, data);
			
			listView.addFooterView(footerView, null, false);
			listView.setAdapter(adapter);
			listView.removeFooterView(footerView);
		}
		
	}
	
	public void setTitle(String title) {
		tvTitle.setText(title);
	}
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.list_header_refresh:
			loadData();
			break;
			
		default:
			break;
		}
	}

	private void home() {
		BlogRadio.home_view.removeAllViews();
		if(BlogRadio.playerView.isCreate)
			BlogRadio.home_view.addView(BlogRadio.playerView.getView());
		else
			BlogRadio.home_view.addView(BlogRadio.playerView.createView(activity,null));
		
		BlogRadio.changeStatusViewDisplay(BlogRadio.VIEWPLAYER);
	}

	/* (non-Javadoc)
	 * @see android.widget.AbsListView.OnScrollListener#onScroll(android.widget.AbsListView, int, int, int)
	 */
	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		// TODO Auto-generated method stub
		if (load(firstVisibleItem, visibleItemCount, totalItemCount))
		{
			loading = true;
			listView.addFooterView(footerView, null, false);
			(new LoadNextPage()).execute();
		}
	}

	/* (non-Javadoc)
	 * @see android.widget.AbsListView.OnScrollListener#onScrollStateChanged(android.widget.AbsListView, int)
	 */
	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// TODO Auto-generated method stub
		
	}
	
	
	protected class LoadNextPage extends AsyncTask<Void, Void, Void>
	{
		private List<Show> data = null;
		
		/* (non-Javadoc)
		 * @see android.os.AsyncTask#onPreExecute()
		 */
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}
		@Override
		protected Void doInBackground(Void... arg0)
		{
			data = new ArrayList<Show>();
			try{
				Server server = new Server(Config.URL_SHOW(page++));
				JSONParser jsonParser = new JSONParser();
				data = jsonParser.getListShow(server.getJsonArray());
				return null;
			}catch(Exception ex)
			{
				ex.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result)
		{
			try {
				HeaderViewListAdapter listAdapter = (HeaderViewListAdapter) listView.getAdapter();
				ListShowAdapter adapter = (ListShowAdapter)listAdapter.getWrappedAdapter();
				if(data != null && data.size() > 0) {
					for (Show value : data)
					{
						adapter.add(value);
					}
					adapter.notifyDataSetChanged();
				} else
					moreRows = false;
				
				listView.removeFooterView(footerView);
				loading = false;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}
	
	protected boolean load(int firstVisibleItem, int visibleItemCount, int totalItemCount)
	{
		if(listView == null || listView.getAdapter() == null)
			return false;
		
		boolean lastItem = firstVisibleItem + visibleItemCount == totalItemCount && listView.getChildAt(visibleItemCount -1) != null && listView.getChildAt(visibleItemCount-1).getBottom() <= listView.getHeight();
		return moreRows && lastItem && !loading;
		
	}
	
}
